package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public AddressBook getById(Long id) {
        Long userId = BaseContext.getCurrentId();
        HashMap map = new HashMap();
        map.put("id", id);
        map.put("userId", userId);
        List<AddressBook> list = addressBookMapper.get(map);
        return list.get(0);
    }

    @Override
    public AddressBook getDefault() {
        Long userId = BaseContext.getCurrentId();
        HashMap map = new HashMap();
        map.put("isDefault", 1);
        map.put("userId", userId);
        List<AddressBook> list = addressBookMapper.get(map);
        return list.get(0);
    }

    @Override
    public List<AddressBook> getAll() {
        Long userId = BaseContext.getCurrentId();
        HashMap map = new HashMap();
        map.put("userId", userId);
        List<AddressBook> list = addressBookMapper.get(map);
        return list;
    }

    @Override
    public void update(AddressBook addressBook) {

        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);

    }

    @Override
    public void setDefault(Integer id) {
        //查询默认地址
        Long userId = BaseContext.getCurrentId();
        HashMap map = new HashMap();
        map.put("isDefault", 1);
        map.put("userId", userId);
        List<AddressBook> list = addressBookMapper.get(map);
          if (list != null && list.size() > 0) {
              AddressBook addressBook = list.get(0);
              //删除默认地址
              addressBook.setIsDefault(0);
              addressBookMapper.update(addressBook);
          }
        //设置当前地址为默认地址
        AddressBook addressBook1 = new AddressBook();
        addressBook1.setId(Long.valueOf(id));
        addressBook1.setIsDefault(1);
        addressBook1.setUserId(userId);
        addressBookMapper.update(addressBook1);
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }

    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);

    }
}
